package com.ebt.m.wiki;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.data.entity.ProductFeature;
import com.ebt.m.data.entity.ProductInfo;
import com.ebt.m.data.middle.InsuranceObj;
import com.ebt.m.data.middle.PolicyNodeMeta;
import com.ebt.m.data.middle.ProductDatainfo;
import com.ebt.m.data.middle.datatype.EAreaBenefit;
import com.ebt.m.data.middle.datatype.EBoolean;
import com.ebt.m.data.middle.datatype.EString;
import com.ebt.m.data.middle.datatype.EUmbrellaBenefit;
import com.ebt.m.data.middle.util.InsuranceFieldUtil;
import com.ebt.m.fragment.LazyFragment;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.imageloader.ImageLoader;
import com.ebt.m.utils.imageloader.ImageLoaderUtil;
import com.ebt.m.widget.Accordion;
import com.ebt.m.wiki.adapter.FeatureAccordionAdapter;
import com.ebt.m.wiki.adapter.WikiAccordionAdapter;
import com.ebt.m.wiki.bean.AreaChartConfig;
import com.ebt.m.wiki.bean.BenefitData;
import com.ebt.m.wiki.event.EOnCalculatorChange;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @author
 * @description 产品-案例说明
 */
public class FrgProductDesc extends LazyFragment implements OnClickListener {

    public static final int IMG_REQUEST_CODE = 1;
    public static final int IMG_RESULT_CODE = 2;
    public static final int FLAG_LOAD_FEATURES = 100;
    public static final int FLAG_LOAD_BENEFITS = 110;

    private Context mContext;
    private ImageView download;
    private LinearLayout mPicsContainer;
    private ImageView mIv_1, mIv_2, mIv_3, mIv_4;
    private Accordion accordionFeature;
    /*区域*/
    private View area_feather;
    private View mainView;
    private View thumbView;
    private TextView mActionPicView;
    private NestedScrollView nestedScrollView;

    private ProductBridgeObj mProductObj;
    private InsuranceObj mInsuranceObj;
    private ProductInfo mProductInfo;
    /*产品特色-s*/
    private ArrayList<ProductFeature> listFeature = new ArrayList<ProductFeature>();
    /*产品特色-e*/

    private Accordion accordionBenefit;
    /*利益图原始数据*/
    private ArrayList<AreaChartConfig> areaChartConfigList;


    public static FrgProductDesc newInstance(ProductBridgeObj mProductObj, boolean isfresh) {
        FrgProductDesc frg = new FrgProductDesc();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", mProductObj);
        bundle.putBoolean("isfresh", isfresh);
        frg.setArguments(bundle);
        return frg;
    }

    public View findViewById(int wikiTab2Tabcontent) {
        return mainView.findViewById(wikiTab2Tabcontent);
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        super.onCreateViewLazy(savedInstanceState);
        mainView = inflater.inflate(R.layout.wiki_frg_product_desc, null);
        nestedScrollView = (NestedScrollView) mainView.findViewById(R.id.nestedview);
        mContext = getActivity();
        initView(mainView);
        initListener();
        initData();
        setContentView(mainView);
         /* 订阅 */
        EventBus.getDefault().register(this);
        onDataSyncPost();
    }

    private void initData() {
        try {
            Bundle bundle = getArguments();
            this.mProductObj = (ProductBridgeObj) bundle.getSerializable("data");
            this.mInsuranceObj = mProductObj.getInsuranceObj();
            this.mProductInfo = mProductObj.getmProduct();
            areaChartConfigList = new ArrayList<AreaChartConfig>();
            if (mProductObj != null) {
                areaChartConfigList.clear();
                areaChartConfigList.addAll(mProductObj.getAreaChartConfigList());
            }
            refreshBasicInfo();
            refreshProductInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void refreshBasicInfo() {
        EBoolean isOfficial = (EBoolean) mInsuranceObj.getNodeValue(InsuranceFieldUtil.FIELDNAME_OFFICIALPICTURE);
        if (isOfficial != null && isOfficial.getValue()) {
            thumbView.setVisibility(View.VISIBLE);
            initPics();
        } else {
            thumbView.setVisibility(View.GONE);
        }
    }


    private void refreshProductInfo() {
        List<BenefitData> benefitDatas = new ArrayList<>();
        Observable.create(/*new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {

            }
        }*/new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                try {
                    HashMap<String, String> modelMap = mProductObj.parseModelToNodeMaps(mProductInfo.modelMapBean, "Model_");
                    String modeStr = modelMap.get("Model_Featurelist");
                    if (modeStr != null && modeStr.contains("N_")) {
                        modeStr = modeStr.replace("N_", "");
                        EString nodeFeatureS = (EString) mInsuranceObj.getNodeValue(modeStr);
                        if (nodeFeatureS != null) {
                            String featureArrayStr = nodeFeatureS.getValue();
                            if (featureArrayStr != null) {
                                String[] nodeStrs = featureArrayStr.split(",");
                                String nodeStr = null;
                                PolicyNodeMeta node = null;
                                ProductFeature pf = null;
                                listFeature.clear();
                                for (int i = 0; i < nodeStrs.length; i++) {
                                    nodeStr = nodeStrs[i];
                                    if (!DataValidation.isEmpty(nodeStr)) {
                                        PolicyNodeMeta pnm = mInsuranceObj.getPolicyNodeMeta(nodeStr);
                                        if (pnm != null) {
                                            if (pnm.getEBTValue() instanceof EAreaBenefit) {
                                                EAreaBenefit eb = (EAreaBenefit) pnm.getEBTValue();
                                                String title = eb.getName();
                                                String valStr = mInsuranceObj.getDictation(nodeStr);
                                                pf = new ProductFeature(title, valStr);
                                            } else if (pnm.getEBTValue() instanceof EUmbrellaBenefit) {
                                                EUmbrellaBenefit eb = (EUmbrellaBenefit) pnm.getEBTValue();
                                                String title = eb.getName();
                                                String valStr = mInsuranceObj.getDictation(nodeStr);
                                                pf = new ProductFeature(title, valStr);
                                            }
                                            listFeature.add(pf);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ///////////////////////////////////////////////////
                try {

                    List<String> validataList = new ArrayList<>();
                    PolicyNodeMeta policyNodeMetaArea = mInsuranceObj.getPolicyNodeMeta("AreaBnftList");
                    if (policyNodeMetaArea != null) {
                        EString eString = (EString) policyNodeMetaArea.getEBTValue();
                        String names = eString.getValue();
                        String[] nameArray = names.split(",");
                        validataList.addAll(Arrays.asList(nameArray));
                    }
                    PolicyNodeMeta policyNodeMetaUmb = mInsuranceObj.getPolicyNodeMeta("UmBnftList");
                    if (policyNodeMetaUmb != null) {
                        EString eString = (EString) policyNodeMetaUmb.getEBTValue();
                        String names = eString.getValue();
                        String[] nameArray = names.split(",");
                        validataList.addAll(Arrays.asList(nameArray));
                    }
                    /*隐藏部分*/
                    PolicyNodeMeta policyNodeHideList = mInsuranceObj.getPolicyNodeMeta(InsuranceFieldUtil.FIELDNAME_HIDELIST);
                    if (policyNodeHideList != null) {
                        EString eString = (EString) policyNodeHideList.getEBTValue();
                        String names = eString.getValue();
                        String[] nameArray = names.split(",");
                        List<String> hideList = Arrays.asList(nameArray);

                        //剔除隐藏.
                        Iterator<String> iterator = validataList.iterator();
                        while (iterator.hasNext()) {
                            String bd = iterator.next();
                            if (hideList.contains(bd)) {
                                iterator.remove();
                            }
                        }
                    }
                    BenefitData benefitData = null;
                    for (int i = 0; i < areaChartConfigList.size(); i++) {
                        benefitData = new BenefitData();
                        benefitData.title = areaChartConfigList.get(i).getTitle();
                        benefitData.value = areaChartConfigList.get(i).getDescription();
                        benefitData.nodeName = areaChartConfigList.get(i).getFieldName();
                        benefitDatas.add(benefitData);
                    }
                    //伞状利益
                    List<EUmbrellaBenefit> umbrellaBenefits = mProductObj.getUmbrellaItems();
                    for (int i = 0; i < umbrellaBenefits.size(); i++) {
                        benefitData = new BenefitData();
                        benefitData.title = umbrellaBenefits.get(i).getName();
                        benefitData.value = umbrellaBenefits.get(i).getDictation();
                        benefitData.nodeName = umbrellaBenefits.get(i).getFieldName();
                        benefitDatas.add(benefitData);
                    }
                    Iterator<BenefitData> iterator = benefitDatas.iterator();
                    while (iterator.hasNext()) {
                        BenefitData bd = iterator.next();
                        if (!validataList.contains(bd.nodeName)) {
                            iterator.remove();
                        }
                    }
                    /*处理title中的算式*/
//                    for (int i = 0; i < benefitDatas.size(); i++) {
//                        String stt = benefitDatas.get(i).title;
//                        String str = mInsuranceObj.operateBenifitDesc(stt);
//                        benefitDatas.get(i).title = str;
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                emitter.onNext(FLAG_LOAD_BENEFITS);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer value) {
                        if (value == FLAG_LOAD_BENEFITS) {
                            if (listFeature.size() > 0) {
                                area_feather.setVisibility(View.VISIBLE);
                                FeatureAccordionAdapter accordionAdapter = new FeatureAccordionAdapter(mContext, accordionFeature, listFeature);
                                accordionFeature.setAdapter(accordionAdapter, -1);
                            }
                            WikiAccordionAdapter accordionAdapter = new WikiAccordionAdapter(getFragmentManager(),mContext, accordionBenefit, benefitDatas);
                            accordionBenefit.setAdapter(accordionAdapter, -1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void initPics() {
        String[] imageUrls = mInsuranceObj.getPictureURL();
        if (imageUrls != null && imageUrls.length > 0) {
            mPicsContainer.setVisibility(View.VISIBLE);
            download.setVisibility(View.GONE);
            for (int i = 0; i < (imageUrls.length > 4 ? 4 : imageUrls.length); i++) {
                if (i == 0) {
                    mIv_1.setVisibility(View.VISIBLE);
                    ImageLoaderUtil.getInstance().loadImage(getContext(), new ImageLoader.Builder().url(imageUrls[i]).imgView(mIv_1).build());
                }
                if (i == 1) {
                    mIv_2.setVisibility(View.VISIBLE);
                    ImageLoaderUtil.getInstance().loadImage(getContext(), new ImageLoader.Builder().url(imageUrls[i]).imgView(mIv_2).build());
                }
                if (i == 2) {
                    mIv_3.setVisibility(View.VISIBLE);
                    ImageLoaderUtil.getInstance().loadImage(getContext(), new ImageLoader.Builder().url(imageUrls[i]).imgView(mIv_3).build());
                }
                if (i == 3) {
                    mIv_4.setVisibility(View.VISIBLE);
                    ImageLoaderUtil.getInstance().loadImage(getContext(), new ImageLoader.Builder().url(imageUrls[i]).imgView(mIv_4).build());
                }
            }
        } else {
            mPicsContainer.setVisibility(View.GONE);
            download.setVisibility(View.VISIBLE);
        }
    }

    private void initView(View view) {
        download = (ImageView) view.findViewById(R.id.img_cover);
        thumbView = view.findViewById(R.id.area_thumb);
        mIv_1 = (ImageView) view.findViewById(R.id.iv_1);
        mIv_2 = (ImageView) view.findViewById(R.id.iv_2);
        mIv_3 = (ImageView) view.findViewById(R.id.iv_3);
        mIv_4 = (ImageView) view.findViewById(R.id.iv_4);
        mActionPicView = (TextView) view.findViewById(R.id.action_pic_view);
        mActionPicView.setOnClickListener(this);
        mPicsContainer = (LinearLayout) view.findViewById(R.id.pics_container);
        mPicsContainer.setOnClickListener(this);
        mPicsContainer.setVisibility(View.GONE);
        download.setVisibility(View.GONE);
        accordionFeature = (Accordion) view.findViewById(R.id.accordion);
        area_feather = view.findViewById(R.id.area_feather);
        accordionBenefit = (Accordion) findViewById(R.id.accordion_benefit);
    }

    private void initListener() {
        download.setOnClickListener(this);
    }


    /**
     * 根据fieldName获得单个节点
     *
     * @param
     * @return PolicyNodeMeta
     * @throws
     * @Description: 根据fieldName获得单个节点
     */
    public static PolicyNodeMeta getNodeByFieldName(String fieldName, List<PolicyNodeMeta> list) {
        if (DataValidation.isEmpty(fieldName)) {
            return null;
        }
        PolicyNodeMeta pnm = null;
        for (int i = 0; i < list.size(); i++) {
            pnm = list.get(i);
            if (pnm != null && fieldName.equalsIgnoreCase(pnm.getFieldName())) {
                return pnm;
            }
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.area_cover:
            case R.id.img_cover:
            case R.id.pics_container:
            case R.id.action_pic_view:
                toViewImg();
                break;
            default:
                break;
        }
    }

    private void toViewImg() {
        ProductDatainfo product = mInsuranceObj.getProduct();
        String[] imageUrls = mInsuranceObj.getPictureURL();
        List<String> list = Arrays.asList(imageUrls);
        Intent intent = new Intent();
        intent.setClass(mContext, ActImgViewer.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", (Serializable) list);
        intent.putExtras(bundle);
        startActivityForResult(intent, IMG_REQUEST_CODE);
        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
        TCAgent.onEvent(mContext, "download_brochure", product.Name);
    }


    /****************************************
     * Event
     ****************************************/

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == IMG_RESULT_CODE) {
            //初始化官方彩页
//            initPics();
        }
    }


    /**
     * @param epc
     * @return void
     * @Description: 订阅计算器修改
     * @throw
     */
    @Subscribe
    public void onEvent(EOnCalculatorChange epc) {
        if (epc != null && epc.isChanged) {
            mProductObj = epc.mProductObj;
            if (mProductObj != null) {
                areaChartConfigList.clear();
                areaChartConfigList.addAll(mProductObj.getAreaChartConfigList());
                refreshProductInfo();
            }
        }
    }

    @Override
    protected void onDestroyViewLazy() {
        super.onDestroyViewLazy();
        EventBus.getDefault().unregister(this);
    }
}
